<template>
	<view class="content">
		<view>
			<u-navbar :background="{background: '#09C15F'}" height='100' :is-back="false">
				<view style="width: 100vw;">
					<view class="nav-address">
						<image class="address-icon" src="../../static/person/weizhi.png"></image>
						<view class="address-name">{{userLocalAddress != '' ? userLocalAddress : '位置未获取'}}</view>
						<image class="arrow" src="../../static/person/xiangxiajiantou(1).png"></image>
					</view>
					<view class="wrap-search">
						<view class="search" @click="intoSearch">
						  <view class="search-btn">
						    <view style="display: flex;align-items: center;">
								<icon class="search-icon" type="search" size="12"/>
								<text>搜索附近优惠</text>
							</view>
						  </view>
						</view>
					</view>
				</view>
			</u-navbar>
		</view>

		<!-- 轮播图 -->
		<view class="wrap" v-if="imgList.length>0">
			<u-swiper @click="swiperChange" :list="imgList" name="img_url" :effect3d="imgList.length>2" indicator-pos="bottomCenter"></u-swiper>
		</view>

		<!-- 分类 -->
		<view class="function_area">
			<view class="area-item" v-for="(item,index) in buttonList" :key="index" @click="toGoodList(item,index)">
				<image :src="item.img_url" style="width: 78rpx;height: 70rpx;"></image>
				<view class="title">{{item.title}}</view>
			</view>
		</view>

		<!-- 优惠券 -->
		<navigator v-if="couponList.length>0" hover-class="none" url="../coupon/coupon_list">
			<view class="advertisement">
			    <image style="width: 100%;height: auto" src="http://file.rzkeji.com/web/locallife/2022/11/16/bc7a362c71419d25e68f3c5ed1a1aaa0.png" mode="widthFix"/>
			</view>
		</navigator>

		<!-- 特惠 -->
        <area-banner ref="area"></area-banner>

		<!--推荐-->
        <view class="recommend-list">
            <view class="recommend-list-title">
                推荐门店（附近）
            </view>
            <view class="null" v-if="recommendData.length==0">
                暂无热门推荐商品~~
            </view>
            <goods-preview v-for="(item,index) in recommendData" :key="index" :item="item"></goods-preview>
            <view class="null" v-if="recommendData.length>0">
                <u-loadmore bg-color='#F9F9F9' color='#B5B5B5' :status="loadingStatus" :icon-type="iconType"
                            :load-text="loadText"/>
            </view>
        </view>

    	<!--客服-->
<!--		<view class="contact-icon" style="bottom: 95rpx" v-if="isLogin">-->
<!--			<contact-button ref="contact">-->
<!--				<img mode="widthFix" src="../../static/home/contact_icon.png"/>-->
<!--			</contact-button>-->
<!--		</view>-->
<!--		<view class="contact-icon" v-else>-->
<!--			<button open-type="getUserInfo" @getuserinfo="login">-->
<!--				<img mode="widthFix" src="../../static/home/contact_icon.png"/>-->
<!--			</button>-->
<!--		</view>-->

	</view>
</template>
<script>
	import goodsPreview from '../../components/goods-preview/index.vue'
  	import contactButton from '../../components/contact-button/index'
    import cartDialog from '../../components/cart-dialog/cart-dialog.vue'
    import areaBanner from '../../components/area-banner/index.vue'
	import {GoodsListPageType} from "../../utils/enum";
  import QQMapWX from "../../utils/qqmap-wx-jssdk.min";
	export default {
		data() {
			return {
				merchant: '',
				imgList:  [],//轮播图
				buttonList: '',//功能区按钮
				recommendData: [],
				errImgUrl: this.$errorImgUrl,//找不到图片的URL
				total: '',
				page: 1,
				loadingStatus: 'loading',
				iconType: 'flower',
				loadText: {
					loadmore: '轻轻上拉',
					loading: '努力加载中',
					nomore: '没有更多了'
				},
				tempMerchantId: '',//判断店铺是否更新的标志
				couponList: [],
				isLogin: '',
				share_merchant_id: '', //通过扫二维码进来获取的门店ID
				isOnLoad: false, //判断onLoad是否执完行了
        userLocal:{},
        QQ_MAP_SDK:'',
        userLocalAddress:'',
			}
		},
		components: {
      		goodsPreview,
      		contactButton,
            cartDialog,
            areaBanner
		},
		onPullDownRefresh() {
			this.initData()
		},
		onReachBottom() {
			if(this.loadingStatus=="loading"||this.total==this.recommendData.length){
				return
			}
			this.page = this.page+1;
			this.getRecommendMedicineList();
		},
		onShow(){
			this.getCurrentMerchant(); //获取门店的相关数据
			this.isLogin = wx.getStorageSync("userToken") //判断用户是否登录
			if(this.$refs.contact){
				this.$refs.contact.updateData() //更新客服信息
			}
		},
		onLoad(options) {
			let scene = decodeURIComponent(options.scene)
			if(options.user_id){
				let invited_user_id = options.user_id
				wx.setStorageSync("invited_user_id",invited_user_id)
				console.log("首页邀请人id",wx.getStorageSync("invited_user_id"))
			}
			if (scene && scene !== 'undefined' && scene !== undefined) {
				let arr = scene.split('=')
				let key = arr[0]
				let merchant_id = arr[1]
				if(key=='merchant_id'){
					wx.setStorageSync("share_merchant_id",merchant_id)
					wx.setStorageSync("merchant",{merchant_id: merchant_id})
					this.getMerchantByQrCode(merchant_id)
				} else if(key=='user_id'){
					wx.setStorageSync("invited_user_id",arr[1] || '')
					console.log("首页邀请人id(通过扫码)",wx.getStorageSync("invited_user_id"))
				}
			}
		},
		onShareAppMessage() {
			return {
				path:'/pages/index/index?user_id='+wx.getStorageSync("user_id")
			}
		},
		methods: {

		    //初始化当前页面数据
            initData() {
                this.getLocaltion();
                this.page = 1;
                this.getBanner();
                this.getIndexButtonList();
                this.getRecommendMedicineList();
                this.$refs.area.getIndexAreaList()
                this.getCouponList()
            },

      getLocaltion(){
        uni.getLocation({
          type: 'gcj02',
          isHighAccuracy: true,
          //定位成功，更新定位结果
          success: res => {

            // if (res.longitude === state.lng && res.latitude === state.lat) {
            //   // 如果经纬度和上一次获取的经纬度一致, 则直接返回上次的, 减少逆解析量
            //   return;
            // }
            console.log('getLocaltion',res)
            this.userLocal.lng = res.longitude
            this.userLocal.lat = res.latitude
            this.userLocal.accuracy = res.accuracy
            this.userLocal.callBackFlag = true;
            this.getAddress()
            // dispatch("getAddress");
          },
          //定位失败回调
          fail: e => {

            // 该错误是由 用户不肯授权位置信息 抛出的错误  小程序开发者工具提示这个错误
            if (e.errMsg === "getLocation:fail auth deny") {

            }

            // 该错误是由 用户不肯授权位置信息 抛出的错误  真机提示这个错误
            if (e.errMsg === "getLocation:fail:auth denied") {

            }

            if (e.errMsg.includes('频繁调用会增加电量损耗')) {
              showToast("请勿频繁操作哦，歇会再试吧 !", "none", 1500);
            }

            // 用户授权了位置信息  但是手机GPS服务没开  则抛出这个错误
            if (e.errMsg.includes("ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF")) {
              // showConfirmModal("检测到您手机未打开GPS服务，请在手机设置中打开GPS服务，以便获取更精确的位置，然后重新进入此页面即可").then(() => {
              //   navigateBack(1);
              // });
            }
          },
          complete: msg => {}
        })
      },
      // 经纬度逆解析, 获取您具体的位置信息
      getAddress() {
        const QQ_MAP_SDK = new QQMapWX({
          key: 'GQCBZ-GVQKQ-VZK5C-GPR4J-KQUNT-PWFJF'
        })
        QQ_MAP_SDK.reverseGeocoder({
          location: {
            latitude: this.userLocal.lat,
            longitude:  this.userLocal.lng,
          },
          success: res => {
            this.userLocalAddress = res.result.address
          },
          fail: err => {
            console.error(err);
          },
          complete: msg => {}
        })
      },
			//获取当前商店
			async getCurrentMerchant() {
				let merchant = wx.getStorageSync("merchant")
				//判断门店是否存在
				if (!merchant) {
					await this.getMerchantByQrCode(1)
					this.initData()
					/*wx.showToast({
						icon: 'none',
						title: '请选择店铺',
						duration: 1500
					})
					setTimeout(()=>{
						wx.navigateTo({
							url: '../chooseShop/chooseShop'
						})
					},1500)*/
				} else {
					this.merchant = merchant;
					if (merchant.merchant_id != this.tempMerchantId) {
						this.tempMerchantId = merchant.merchant_id;
						this.initData()
					}
				}
			},

			//获取通过二维码进来的店铺信息
			async getMerchantByQrCode(id) {
				let res= await this.$api.getMerchantList({
					merchant_id: id
				},this.$baseUrl)
				if(res.data.level==="success"){
					let merchant = res.data.data[0]
					if(!merchant){
						return
					}
					this.merchant = merchant
					wx.setStorageSync("merchant",merchant)
				}
			},

			//进入选择商店页面
			intoChooseShop() {
				wx.navigateTo({
					url: '../chooseShop/chooseShop'
				})
			},

			//进入搜索页面
			intoSearch() {
				wx.navigateTo({
					url: '../search/search'
				})
			},

			//获取轮播图
			async getBanner(){
			  let res=await this.$api.getBannerList({
				  merchant_id: this.merchant.merchant_id
			  },this.$baseUrl);
			  if(res.data.level=='success'){
			    this.imgList=res.data.data;
			    wx.stopPullDownRefresh()
			  }
			},

			//获取首页功能区按钮
			async getIndexButtonList(){
			  let res=await this.$api.getIndexButtonList({
				  merchant_id: this.merchant.merchant_id
			  },this.$baseUrl);
			  if(res.data.level=='success'){
			    this.buttonList=res.data.data;
			    wx.stopPullDownRefresh()
			  }
			},

			//优惠券列表
			async getCouponList(){
			    let res=await this.$api.getCouponList({
			    	merchant_id: this.merchant.merchant_id,
			    	page: 1
			    },this.$baseUrl);
			    if(res.data.level=='success'){
			        this.couponList = res.data.data
			    }
			},

			//获取推荐商品
			async getRecommendMedicineList(){
			  this.loadingStatus = 'loading';
			  let res=await this.$api.getMerchantMedicineList({
				  merchant_id: this.merchant.merchant_id,
				  limit: 6,
				  page: this.page
			  },this.$baseUrl);
			  if(res.data.level=='success'){
				  if(this.page == 1){
					  this.recommendData = res.data.data.medicine_info;
				  } else{
					  if(res.data.data.medicine_info.length == 0){
						  this.page--;
					  } else{
						  this.recommendData = this.recommendData.concat(res.data.data.medicine_info)
					  }
				  }
				  this.total = res.data.page_info.total;
				//loading状态
				if(this.recommendData.length==this.total){
					this.loadingStatus = 'nomore'
				} else{
					this.loadingStatus = 'loadmore'
				}
			  } else{
				  wx.showToast({
				  	title: res.data.message,
					icon: 'none',
					duration: 1500
				  })
			  }
			  wx.stopPullDownRefresh()
			},

			//跳转商品列表页面
			toGoodList(item,index){
				let linkUrl = item.link_url
				if(!linkUrl){
					wx.navigateTo({
						url: `../goodsList/goodList?classifyId=${item.classify_id}&name=${item.title}&type=${GoodsListPageType.BUTTON}`
					})
				} else if(linkUrl.search('http')!=-1){
					wx.navigateTo({
						url: '../out/out?url='+linkUrl
					})
				}  else{
					wx.navigateToMiniProgram({
						appId: linkUrl
					})
				}
			},

			//轮播图点击事件
			swiperChange(index) {
				let linkUrl = this.imgList[index].link_url
				wx.navigateTo({
					url: linkUrl
				})
			},

			//微信授权
			async login(e) {
				const data = await this.$currency.bindGetUserInfo(e.detail.userInfo,this.$baseUrl)
				if(data=="success"){
					await this.$currency.getUserInfos(this.$baseUrl) //登录后要获取用户信息
				}
				this.isLogin = wx.getStorageSync("userToken") //判断用户是否登录
			},

		}
	}
</script>

<style scoped lang="scss">
	@import "../../common/css/mixin";

	.nav-address{
		width: 100%;
		display: flex;
		align-items: center;
		.address-icon{
			width: 19px;
			height: 19px;
			margin: 0 10px;
		}
		.address-name{
			max-width: 50%;
			@include ellipsis(1);
			color: #FFFFFF;
		}
		.arrow{
			width: 11px;
			height: 9px;
			margin-left: 8px;
		}
	}

	.wrap-search{
		padding-top: 10px;
		height: 50px;
	}

	.search{
	  width: calc(100vw - 20px);
	  height: 35px;
	  padding: 5px 10px;

	  .search-btn{
	    width: calc(100% - 60px);
	    position: relative;
	    padding: 0 30px;
	    height: 35px;
	    line-height: 35px;
	    border-radius: 50rpx;
	    border: 1rpx solid #eeeeee;
	    font-size: 12px;
	    color: #858585;
	    /* background: rgba(255,255,255,0.8); */
		background-color: #fbfbfb;
		display: flex;
		align-items: center;
		justify-content: center;
	    .search-icon{
	      position: relative;
	      top: 15rpx;
	      /* left: 25rpx; */
		  margin-right: 8px;
	    }
	  }
	}

	.function_area{
		display: flex;
		justify-content: left;
		flex-wrap: wrap;
		padding: 24rpx;
		.area-item{
			/* width: 48px;
			margin: 10px; */
			width: calc((100vw - 48rpx)/5);
			margin: 10px 0;
			text-align: center;
		}
		.title{
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 1;
			overflow: hidden;
			font-size: 24rpx;
		}
	}

	.advertisement{
	    width: calc(100vw - 24px);
		padding: 0 12px;
	    margin: 0 auto 10px auto
	}

	.preferential{
		padding: 0 12px;
		margin-bottom: 15px;
		.spec-background{
			width: 100%;
			background-image: url(../../static/home/test.png);
			background-size: 100% auto;
			background-repeat: no-repeat;
			overflow: hidden;
		}
		.no-wrap{
		  display: -webkit-box;
		  -webkit-box-orient: vertical;
		  -webkit-line-clamp: 1;
		  overflow: hidden;
		  white-space: normal;
		  font-size: 13px;
		  padding: 0 5px;
		  min-height: 13px;
		}

		.page-section-spacing {
			padding: 0 8px;
		}

		.scroll-view_H {
			white-space: nowrap;
			width: 100%
		}

		.scroll-view-item_H {
			display: inline-block;
			width: 110px;
			text-align: center;
			/* border: 1px solid #EEEEEE; */
			border-radius: 10rpx;
			margin-right: 10px;
			padding: 10px 10px 0;
			background-color: #FFFFFF;
			.item-img{
				width: 110px;
				height: 110px;
			}
		}
		.scroll-view-item_H:last-child{
			margin-right: 0;
		}
	}

	.coupon{
		padding: 12px;
		background-color: #FFFFFF;
		display: flex;
		justify-content: center;
		image{
			width: calc(100% - 24px);
		}
	}

	.recommend-list{
	  @include flexWrap(flex-start,flex-start);
	  flex-direction: row;
	  justify-content: space-between;
	  width: 100%;
        box-sizing: border-box;
	  background-color: #F9F9F9;
	  padding: 20rpx;
	  .recommend-list-title{
	    width: 100%;
		font-size: 18px;
		font-weight: bold;
	    padding: 10px 0 20px;
	  }
	  .null{
		width: 100%;
		padding: 40rpx ;
		text-align: center;
		min-height: 40rpx;
		line-height: 40rpx;
		font-size: 28rpx;
		color: #B5B5B5;
	  }
	}

	.contact-icon{
		position: fixed;
		right: 0;
		bottom: 100rpx;
		background: none;
		img{
			width: 100px;
			height: auto;
		}
		button{
			width:100%;
			display: flex;
			font-size: 14px;
			justify-content: space-between;
			align-items: center;
			background: none;
			padding: 0;
		}
		button::after{
			border: none;
		}
	}

</style>
